﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;

namespace System
{
    /// <summary>
    /// 表示消息收发处理器
    /// </summary>
    public class MessagingCenter
    {
        /// <summary>
        /// 表示<see cref="MessagingCenter"/>的对象实例
        /// </summary>
        private static MessagingCenter _instance { get; } = new MessagingCenter();

        /// <summary>
        /// 表示默认的订阅/发布对象
        /// </summary>
        private static readonly object _object = new object();

        class Sender : Tuple<string, Type, Type>
        {
            public Sender(string message, Type senderType, Type argType) : base(message, senderType, argType)
            {
            }
        }

        delegate bool Filter(object sender);

        class MaybeWeakReference
        {
            WeakReference DelegateWeakReference { get; }
            object DelegateStrongReference { get; }

            readonly bool _isStrongReference;

            public MaybeWeakReference(object subscriber, object delegateSource)
            {
                if (subscriber.Equals(delegateSource))
                {
                    // The target is the subscriber; we can use a weakreference
                    DelegateWeakReference = new WeakReference(delegateSource);
                    _isStrongReference = false;
                }
                else
                {
                    DelegateStrongReference = delegateSource;
                    _isStrongReference = true;
                }
            }

            public object Target => _isStrongReference ? DelegateStrongReference : DelegateWeakReference.Target;
            public bool IsAlive => _isStrongReference || DelegateWeakReference.IsAlive;
        }

        class Subscription : Tuple<WeakReference, MaybeWeakReference, MethodInfo, Filter>
        {
            public Subscription(object subscriber, object delegateSource, MethodInfo methodInfo, Filter filter)
                : base(new WeakReference(subscriber), new MaybeWeakReference(subscriber, delegateSource), methodInfo, filter)
            {
            }

            public WeakReference Subscriber => Item1;
            MaybeWeakReference DelegateSource => Item2;
            MethodInfo MethodInfo => Item3;
            Filter Filter => Item4;

            public void InvokeCallback(object sender, object args)
            {
                if (!Filter(sender))
                {
                    return;
                }

                if (MethodInfo.IsStatic)
                {
                    MethodInfo.Invoke(null, MethodInfo.GetParameters().Length == 1 ? new[] { sender } : new[] { sender, args });
                    return;
                }

                var target = DelegateSource.Target;

                if (target == null)
                {
                    return; // Collected 
                }

                MethodInfo.Invoke(target, MethodInfo.GetParameters().Length == 1 ? new[] { sender } : new[] { sender, args });
            }

            public bool CanBeRemoved()
            {
                return !Subscriber.IsAlive || !DelegateSource.IsAlive;
            }
        }

        readonly Dictionary<Sender, List<Subscription>> _subscriptions =
            new Dictionary<Sender, List<Subscription>>();

        /// <summary>
        /// 发送消息
        /// </summary>
        /// <typeparam name="TSender">表示发送方对象的类型</typeparam>
        /// <typeparam name="TArgs">表示发送参数的类型</typeparam>
        /// <param name="sender">表示发送方对象</param>
        /// <param name="message">表示消息唯一名称</param>
        /// <param name="args">表示发送参数</param>
        public static void Send<TSender, TArgs>(TSender sender, string message, TArgs args) where TSender : class
        {
            if (sender == null)
                throw new ArgumentNullException(nameof(sender));
            _instance.InnerSend(message, typeof(TSender), typeof(TArgs), sender, args);
        }

        /// <summary>
        /// 发送消息
        /// </summary>
        /// <typeparam name="TArgs">表示发送参数的类型</typeparam>
        /// <param name="message">表示消息唯一名称</param>
        /// <param name="args">表示发送参数</param>
        public static void Send<TArgs>(string message, TArgs args)
        {
            Send(_object, message, args);
        }

        /// <summary>
        /// 发送消息
        /// </summary>
        /// <typeparam name="TSender">表示发送方对象的类型</typeparam>
        /// <param name="sender">表示发送方对象</param>
        /// <param name="message">表示消息唯一名称</param>
        public static void Send<TSender>(TSender sender, string message) where TSender : class
        {
            if (sender == null)
                throw new ArgumentNullException(nameof(sender));
            _instance.InnerSend(message, typeof(TSender), null, sender, null);
        }

        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="message">表示消息唯一名称</param>
        public static void Send(string message)
        {
            Send(_object, message);
        }

        /// <summary>
        /// 消息订阅
        /// </summary>
        /// <typeparam name="TSender">表示需要订阅的消息对象的类型，可以使用<see langword="object"/>代替处理，需要发送和接收方都使用<see langword="object"/></typeparam>
        /// <typeparam name="TArgs">表示需要订阅的消息对象的发送参数的类型</typeparam>
        /// <param name="subscriber">表示订阅者对象</param>
        /// <param name="message">表示消息唯一名称</param>
        /// <param name="callback">表示回调函数</param>
        /// <param name="source">表示消息发送方的对象</param>
        public static void Subscribe<TSender, TArgs>(object subscriber, string message, Action<TSender, TArgs> callback, TSender source = null) where TSender : class
        {
            //Instance.Subscribe(subscriber, message, callback, source);
            if (subscriber == null)
                throw new ArgumentNullException(nameof(subscriber));
            if (callback == null)
                throw new ArgumentNullException(nameof(callback));

            var target = callback.Target;

            Filter filter = sender =>
            {
                var send = (TSender)sender;
                return (source == null || send == source);
            };

            _instance.InnerSubscribe(subscriber, message, typeof(TSender), typeof(TArgs), target, callback.GetMethodInfo(), filter);
        }

        /// <summary>
        /// 消息订阅
        /// </summary>
        /// <typeparam name="TArgs">表示需要订阅的消息对象的发送参数的类型</typeparam>
        /// <param name="message">表示消息唯一名称</param>
        /// <param name="callback">表示回调函数</param>
        public static void Subscribe<TArgs>(string message, Action<TArgs> callback)
        {
            Action<object, TArgs> action = new Action<object, TArgs>((o, args) =>
            {
                callback.Invoke(args);
            });
            Subscribe(_object, message, action, _object);
        }

        /// <summary>
        /// 消息订阅
        /// </summary>
        /// <typeparam name="TSender">表示需要订阅的消息对象的类型，可以使用<see langword="object"/>代替处理，需要发送和接收方都使用<see langword="object"/></typeparam>
        /// <param name="subscriber">表示订阅者对象</param>
        /// <param name="message">表示消息唯一名称</param>
        /// <param name="callback">表示回调函数</param>
        /// <param name="source">表示消息发送方的对象</param>
        public static void Subscribe<TSender>(object subscriber, string message, Action<TSender> callback, TSender source = null) where TSender : class
        {
            if (subscriber == null)
                throw new ArgumentNullException(nameof(subscriber));
            if (callback == null)
                throw new ArgumentNullException(nameof(callback));

            var target = callback.Target;

            Filter filter = sender =>
            {
                var send = (TSender)sender;
                return (source == null || send == source);
            };

            _instance.InnerSubscribe(subscriber, message, typeof(TSender), null, target, callback.GetMethodInfo(), filter);
        }

        /// <summary>
        /// 消息订阅
        /// </summary>
        /// <param name="message">表示消息唯一名称</param>
        /// <param name="callback">表示回调函数</param>
        public static void Subscribe(string message, Action callback)
        {
            Action<object> action = new Action<object>((o) =>
            {
                callback.Invoke();
            });
            Subscribe(_object, message, action, _object);
        }

        /// <summary>
        /// 取消订阅
        /// </summary>
        /// <typeparam name="TSender">消息发送方对象的类型</typeparam>
        /// <typeparam name="TArgs">表示发送参数的类型</typeparam>
        /// <param name="subscriber">订阅者对象</param>
        /// <param name="message">表示消息唯一名称</param>
        public static void Unsubscribe<TSender, TArgs>(object subscriber, string message) where TSender : class
        {
            _instance.InnerUnsubscribe(message, typeof(TSender), typeof(TArgs), subscriber);
        }

        /// <summary>
        /// 取消订阅
        /// </summary>
        /// <typeparam name="TSender">消息发送方对象的类型</typeparam>
        /// <param name="subscriber">订阅者对象</param>
        /// <param name="message">表示消息唯一名称</param>
        public static void Unsubscribe<TSender>(object subscriber, string message) where TSender : class
        {
            _instance.InnerUnsubscribe(message, typeof(TSender), null, subscriber);
        }

        void InnerSend(string message, Type senderType, Type argType, object sender, object args)
        {
            if (message == null)
                throw new ArgumentNullException(nameof(message));
            var key = new Sender(message, senderType, argType);
            if (!_subscriptions.ContainsKey(key))
                return;
            List<Subscription> subcriptions = _subscriptions[key];
            if (subcriptions == null || !subcriptions.Any())
                return; // should not be reachable

            // 如果不重新从集合中取一遍，那么将有可能你想使用的时候，集合已经被外部更改，那时就不存在此消息了
            List<Subscription> subscriptionsCopy = subcriptions.ToList();
            foreach (Subscription subscription in subscriptionsCopy)
            {
                if (subscription.Subscriber.Target != null && subcriptions.Contains(subscription))
                {
                    subscription.InvokeCallback(sender, args);
                }
            }
        }

        void InnerSubscribe(object subscriber, string message, Type senderType, Type argType, object target, MethodInfo methodInfo, Filter filter)
        {
            if (message == null)
                throw new ArgumentNullException(nameof(message));
            var key = new Sender(message, senderType, argType);
            var value = new Subscription(subscriber, target, methodInfo, filter);
            if (_subscriptions.ContainsKey(key))
            {
                _subscriptions[key].Add(value);
            }
            else
            {
                var list = new List<Subscription> { value };
                _subscriptions[key] = list;
            }
        }

        void InnerUnsubscribe(string message, Type senderType, Type argType, object subscriber)
        {
            if (subscriber == null)
                throw new ArgumentNullException(nameof(subscriber));
            if (message == null)
                throw new ArgumentNullException(nameof(message));

            var key = new Sender(message, senderType, argType);
            if (!_subscriptions.ContainsKey(key))
                return;
            _subscriptions[key].RemoveAll(sub => sub.CanBeRemoved() || sub.Subscriber.Target == subscriber);
            if (!_subscriptions[key].Any())
                _subscriptions.Remove(key);
        }
    }

}
